from django.db import models

# Create your models here.

class UserInfo(models.Model):
    '''
    用户表
    '''
    username = models.CharField(verbose_name="用户名", max_length=32)
    password = models.CharField(verbose_name="密码", max_length=64)
    email = models.EmailField()
    # blank = True 表示表单允许为空 null=True 表示数据库的该字段可以为空
    roles = models.ManyToManyField(verbose_name="拥有角色", to="Role", blank=True)
    ctime = models.DateTimeField(verbose_name='时间', auto_now_add=True)

    #admin声明表名
    class Meta:
        verbose_name_plural = "用户表"

    def __str__(self):
        return "{}".format(self.username)


class Role(models.Model):
    '''
    角色表
    '''
    caption = models.CharField(verbose_name="角色名称", max_length=32)
    permissions = models.ManyToManyField(verbose_name="拥有权限", to="Permission", blank=True)
    ctime = models.DateTimeField(verbose_name='时间', auto_now_add=True)

    class Meta:
        verbose_name_plural = "角色表"

    def __str__(self):
        return "{}".format(self.caption)

class Permission(models.Model):
    '''
    权限表
    '''
    caption = models.CharField(verbose_name="权限名", max_length=32)
    url = models.CharField(verbose_name="URL", max_length=128, blank=True, null=True)
    code = models.CharField(verbose_name="权限代码", max_length=64)
    is_menu = models.BooleanField(verbose_name="是否为菜单", default=False)
    group = models.ForeignKey(verbose_name='所属组', to="Memu", related_name="permissoins",
                              limit_choices_to={"is_group": True})
    ctime = models.DateTimeField(verbose_name='时间', auto_now_add=True)

    class Meta:
        verbose_name_plural = "权限表"

    def __str__(self):
        return "{}".format(self.caption)


class Memu(models.Model):
    '''
    菜单表
    '''
    caption = models.CharField(verbose_name="菜单名称", max_length=64)
    is_group = models.BooleanField(verbose_name="是否为组", default=False)
    parent = models.ForeignKey(verbose_name="菜单父ID", to="Memu", related_name='p', null=True, blank=True,
                               limit_choices_to={'is_group': False})
    ctime = models.DateTimeField(verbose_name='时间', auto_now_add=True)

    class Meta:
        verbose_name_plural = "菜单与组表"

    def __str__(self):
        parent = self.parent
        menu_list = [self.caption, ]
        while True:
            if parent:
                menu_list.append(parent.caption)
                parent = parent.parent
            else:
                break
        return ("-").join(menu_list)
